package edu.cuit.avatar.service.impl;

import edu.cuit.avatar.entity.Book;
import edu.cuit.avatar.service.BookService;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 图书业务实现类————将图书保存进内存
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/15 15:28
 */
public class BookServiceImplInMemory implements BookService {
    //ConcurrentHashMap：线程安全的HashMap
    private static final Map<Integer, Book> REPOSITORY = new ConcurrentHashMap<>();
    private static AtomicInteger idGenerator  = new AtomicInteger();
    @Override
    public Integer save(Book book) {
        //1.生成id并将该id设置给book实体
        var id = idGenerator.getAndIncrement();
        //2.将图书信息保存进仓库
        REPOSITORY.put(id, book);
        //3.返回生成的id
        return id;
    }

    @Override
    public void removeById(Serializable id) {
        REPOSITORY.remove(id);
    }

    @Override
    public void updateById(Book book) {
        if(REPOSITORY.containsKey(book.getId()))
            REPOSITORY.replace(book.getId(), book);
    }

    @Override
    public List<Book> findAll() {
        return new ArrayList<>(REPOSITORY.values());
    }

    @Override
    public Book findById(Serializable id) {
        return REPOSITORY.get(id);
    }
}
